import { math } from "cc";
import NOVBase from "./NOVBase";
import { Collider2D } from "cc";
import { PhysicsSystem2D } from "cc";
import { v2 } from "cc";
import { Vec2 } from "cc";
import { Vec3 } from "cc";
import { v3 } from "cc";

//简单的避障
export default class NOV2DSimple extends NOVBase {

    //采用CC的碰撞器
    collide:Collider2D;

    // //是否添加速度安全距离
    // isAddSpeedSafe:boolean = false;

    // //安全距离
    // safe:number = 1;

    constructor(collide:Collider2D,safe:number = 1){
        super();
        this.collide = collide;
        // this.safe = safe;
    }

    //移动
    move(move: math.Vec3,isOV:boolean = true):Vec3 {

        let worldPos = this.collide.node.getWorldPosition();
        let diff = move.clone().subtract(worldPos);
        let aabb = this.collide.worldAABB.clone();
        aabb.x += diff.x;
        aabb.y += diff.y;
        // let safe = this.safe; 
        // if(this.isAddSpeedSafe){
        //     safe += diff.length();
        // }
        // aabb.width += safe;
        // aabb.height += safe;

        let aabbs = PhysicsSystem2D.instance.testAABB(aabb).filter(collide => collide != this.collide);
        let movePos = !(aabbs.length) ? move : null;

        if(aabbs[0] && isOV){
            let len = move.clone().subtract(worldPos).length();
            let aabb2 = this.collide.worldAABB.clone();

            //试图向前避障
            if((move.x - worldPos.x) <= 0)
                aabb2.x -= len;
            else
                aabb2.x += len;
            if(!(aabb2.intersects(aabbs[0].worldAABB))){
                return this.move(v3(worldPos.x+len,worldPos.y,worldPos.z),false)
            }

            aabb2 = this.collide.worldAABB.clone();
            //试图向上和向下避障
            if(aabb.center.y > aabbs[0].worldAABB.center.y){
                aabb2.y += len;
                if(!(aabb2.intersects(aabbs[0].worldAABB))){
                    return this.move(v3(worldPos.x,worldPos.y + len,worldPos.z),false)
                }
            }else{
                aabb2.y -= len;
                if(!(aabb2.intersects(aabbs[0].worldAABB))){
                    return this.move(v3(worldPos.x,worldPos.y - len,worldPos.z),false)
                }
            }
        }

        return movePos;
    }

    //移动目标
    moveTo(move: math.Vec3):Vec3 {
        if(PhysicsSystem2D.instance.testAABB(this.collide.worldAABB).filter(collide => collide != this.collide).length)
            return move;
        return this.move(move,true);
    }

}

